package moniPriortyQueue;

import java.util.Arrays;

public class TestHeap {
    private int[] elem;
    private int usedSized;

    public TestHeap() {
        this.elem = new int[10];
    }

    public void initHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSized++;
        }
    }

    //创建大根堆
    public void createHeap() {
        for (int parent = (usedSized - 1 - 1) / 2; parent >= 0; parent--) {//从最后一棵子树根节点到上一棵子树根节点直至
            //向下调整
            shiftDown(parent, usedSized);
        }
    }

    //向下调整
    private void shiftDown(int parent, int usedSized) {
        int child = (2 * parent) + 1;
        while (child < usedSized) {//左孩子下标-->越界可能
            //求左右孩子最大值 child
            if (child + 1 < usedSized && elem[child] < elem[child + 1]) {
                child++;
            }
            //交换 这个最小子树的左右孩子最大值 与 此树根节点
            if(elem[child]>elem[parent]){
                swap(child,parent);
                parent=child;
                child=2*parent+1;
            }else{
                break;
            }
        }
    }

    private void swap(int i,int j){
        int tmp=elem[i];
        elem[i]=elem[j];
        elem[j]=tmp;
    }

    //插入
    public void offer(int val){
        if(isFull()){
            this.elem= Arrays.copyOf(elem,2*elem.length);
        }
        this.elem[usedSized]=val;
        //向上调整
        shiftUp(usedSized);

        //调整完++
        usedSized++;
    }

    private void shiftUp(int child) {
        //找到双亲
        int parent=(child-1)/2;
        while (child>0){
            if(elem[child]>elem[parent]){
                swap(child,parent);
                child=parent;
                parent=(child-1)/2;
            }else {
                break;
            }
        }
    }



    public boolean isFull(){
        return usedSized== elem.length;
    }


    //删除
    public int poll(){
        int tmp=elem[0];
        swap(0,usedSized-1);
        usedSized--;//删掉最后一个元素 65
        shiftDown(0,usedSized);
        return tmp;
    }
}




























